﻿using Lib.Security;
using Lib.WPF.Core;
using Lib.WPF.Entitys;
using System.Diagnostics;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;



namespace Lib.WPF.ViewModels;
/// <summary>
/// 
/// </summary>
public class LogOn : ViewModelBase {
    /// <summary>
    /// 构造函数
    /// </summary>
    public LogOn() {
        // 
        this.ConfigsKey = "AppSettings";
        //
        this.LoginConfigsKey = "LoginConfigs";
        //
        var isSaveConfigs = false;
        //
        if (Debugger.IsAttached) {
            //
            this.IsBinary = false;
            //
            this.SecretKey = null;
        } else {
            //
            this.IsBinary = true;
            //
            this.SecretKey = Password.CPUID;
        }
        /* 加载 AppSettings 配置 */

        var FileConfigs = $"{this.ConfigsKey}.json";

        if (Common.JSonDocument(FileConfigs)) {
            //
            isSaveConfigs = true;
            //
            this.Configs = Common.GetFile<Configs>(FileConfigs);

        } else {
            this.Configs = Common.GetFile<Configs>(FileConfigs, this.IsBinary, this.SecretKey);
        }
        //
        if (this.Configs == null) {
            //
            isSaveConfigs = true; 
            //
            this.Configs = new Configs();
        }
        //
        if (string.IsNullOrEmpty(this.Configs.SecretKey)) {
            //
            isSaveConfigs = true;
            //
            this.Configs.SecretKey = Password.CPUID;
        }
        //
        Session.Set(this.ConfigsKey, this.Configs);

        /* 修改 AppSettings 配置，并保存 */

        if (isSaveConfigs) {
            Common.SaveFile<Configs>(this.Configs, $"{this.ConfigsKey}.json", this.IsBinary, this.SecretKey);
        }

        /* 加载 LoginConfigs 配置 */

        this.LoginConfigs = Common.GetFile<LoginConfigs>($"{this.LoginConfigsKey}.json", this.IsBinary, this.SecretKey);
        //
        if (this.LoginConfigs == null) {
            this.LoginConfigs = new LoginConfigs();
        }
        //
        this.LoginName = this.LoginConfigs.LoginName;
        this.IsAutoLogon = this.LoginConfigs.IsAutoLogon;
        this.IsKeepPassword = this.LoginConfigs.IsKeepPassword;
        //
        if (this.IsKeepPassword && !string.IsNullOrEmpty(this.LoginConfigs.LoginPassword)) {
            this.LoginPassword = Password.Decrypt(this.LoginConfigs.LoginPassword, this.Configs.SecretKey);
        }
        //
        this.InitCommand();
        //
        this.InitLoginCommand();

    }
    /// <summary>
    /// 初始化（Window.Loaded += Initialize）
    /// </summary>
    public override void Initialize() {
        //
        this.AutoLogon();
    }
    /// <summary>
    /// 
    /// </summary>
    public async void AutoLogon() {
        if (this.IsAutoLogon && !string.IsNullOrEmpty(this.LoginPassword)) {
            this.LoginEnter = Find<Button>("LoginEnter");
            var PasswordBox = Find<PasswordBox>("PasswordBox");
            if (PasswordBox != null) {
                this.LoginEnter.Content = "登录中...";
                this.LoginState = 1;
                await Task.Delay(4000);
                this.LoginState += 1;
                this.Login.Execute(PasswordBox);
                this.LoginState = 0;
            }
        }
    }
    /// <summary>
    /// 
    /// </summary>
    public void InitLoginCommand() {

        // 登录验证功能
        this.Login = new Command(Sender => {
            if (Sender != null) {
                if (this.LoginState != 0 && this.LoginState != 2) {
                    this.LoginState = 3;
                    this.LoginEnter.Content = "登录";
                    return;
                }
                var Box = Sender as PasswordBox;
                var isPassed = false;
                var Password = Box?.Password;
                var LoginPicture = this.LoginConfigs.DefaultPicture;
                int? UID = null;
                /*
                 * 远程登录验证功能写在此处，通过设置 isPassed = True 返之设为 False
                 */
                if (!string.IsNullOrEmpty(this.LoginName) && !string.IsNullOrEmpty(Password)) {
                    isPassed = true;
                }
                /* 
                 * 已审核通过处理 
                 */
                if (isPassed) {
                    //
                    LoginEntity That = null;
                    //
                    Password = Security.Password.Encrypt(Password, this.Configs.SecretKey);
                    // 
                    That = new LoginEntity(this.LoginName, Password, LoginPicture, UID, this.IsKeepPassword);

                    /* 修改 LoginConfigs 配置 */

                    this.LoginConfigs.LoginDateTime = DateTime.Now;
                    //
                    this.LoginConfigs.LoginName = That.LoginName;
                    //
                    this.LoginConfigs.LoginPassword = That.Password;
                    //
                    this.LoginConfigs.LoginPicture = That.Picture;
                    //
                    this.LoginConfigs.IsKeepPassword = That.IsKeepPassword;
                    //
                    this.LoginConfigs.IsAutoLogon = this.IsAutoLogon;
                    //
                    this.LoginConfigs.LoginEntitys.RemoveAll(P => P.LoginName == this.LoginName);
                    //
                    this.LoginConfigs.LoginEntitys.Insert(0, That);
                    //
                    if (this.LoginConfigs.LoginEntitys.Count > 10) {
                        this.LoginConfigs.LoginEntitys.RemoveAt(9);
                    }
                    //
                    Common.SaveFile<LoginConfigs>(this.LoginConfigs, $"{this.LoginConfigsKey}.json", this.IsBinary, this.SecretKey);
                    //
                    Session.Set(this.LoginConfigsKey, this.LoginConfigs);
                    //
                    Session.Set("LoginEntity", That);
                    //
                    this.Window.DialogResult = true;
                    this.Window.Close();

                }
            }

        });
    }
    /// <summary>
    /// 注册帐号、找回密码功能
    /// </summary>
    public void InitCommand() {
        //
        this.CMD = new Command(P => {
            if (P != null) {
                var Key = P?.ToString();
                try {
                    switch (Key) {
                        case "Selection":
                            this.IsKeepPassword = this.LoginEntity.IsKeepPassword;
                            this.LoginName = this.LoginEntity.LoginName;
                              if (this.LoginEntity.IsKeepPassword) {
                                this.LoginPassword = Password.Decrypt(this.LoginEntity.Password, this.Configs.SecretKey);
                            } else {
                                this.LoginPassword = null;
                            }
                            this.IsPopupOpen = false;
                            this.AutoLogon();
                            break;
                        case "Register":
                        case "Password":
                            MessageBox.Show("此功能正在完善中...");
                            break;
                        default:
                            break;
                    }
                } catch (Exception ex) {
                    MessageBox.Show($"执行“{Key}”命令出错！\n\n错误信息：{ex.Message}");
                }
            }
        });

    }
    /// <summary>
    /// 
    /// </summary>
    private Button LoginEnter { get; set; }
    /// <summary>
    /// 是否登录中
    /// </summary>
    private int LoginState { get; set; }
    /// <summary>
    /// 
    /// </summary>
    private string ConfigsKey { get; set; }
    /// <summary>
    /// 
    /// </summary>
    private string LoginConfigsKey { get; set; }
    /// <summary>
    /// 密钥
    /// </summary>
    private string SecretKey { get; set; }
    /// <summary>
    /// 
    /// </summary>
    private bool IsBinary { get; set; }
    /// <summary>
    /// 登录配置
    /// </summary>
    public LoginConfigs LoginConfigs { get; set; }
    /// <summary>
    /// 全局配置
    /// </summary>
    public Configs Configs { get; set; }
    /// <summary>
    /// 
    /// </summary>
    public ICommand CMD { get; set; }
    /// <summary>
    /// 登录
    /// </summary>
    public ICommand Login { get; set; }


    /// <summary>
    /// 
    /// </summary>
    public bool IsPopupOpen {
        get {
            return this.GetValue(x => x.IsPopupOpen);
        }
        set {
            this.SetValue(x => x.IsPopupOpen, value);
        }
    }
    /// <summary>
    /// 选择的帐号
    /// </summary>
    public LoginEntity LoginEntity {
        get {
            return this.GetValue(x => x.LoginEntity);
        }
        set {
            this.SetValue(x => x.LoginEntity, value);
        }
    }
    /// <summary>
    /// 登录帐号
    /// </summary>
    public string LoginName {
        get {
            return this.GetValue(x => x.LoginName);
        }
        set {
            this.SetValue(x => x.LoginName, value);
        }
    }
    /// <summary>
    /// 登录密码（明文）
    /// </summary>
    public string LoginPassword {
        get {
            return this.GetValue(x => x.LoginPassword);
        }
        set {
            this.SetValue(x => x.LoginPassword, value);
        }
    }
    /// <summary>
    /// 是否自动登录
    /// </summary>
    public bool IsAutoLogon {
        get {
            return this.GetValue(x => x.IsAutoLogon);
        }
        set {
            this.SetValue(x => x.IsAutoLogon, value);
        }
    }
    /// <summary>
    /// 是否记住密码
    /// </summary>
    public bool IsKeepPassword {
        get {
            return this.GetValue(x => x.IsKeepPassword);
        }
        set {
            this.SetValue(x => x.IsKeepPassword, value);
        }
    }

}
